<template>
  <div class="goods-sku">
    <van-sku
      v-model="isShow"
      :sku="skuData"
      :goods="goods"
      :goods-id="goods.goodsId"
      :initial-sku="initialSku"
      :hide-stock="skuData.hide_stock"
      :close-on-click-overlay="true"
      @buy-clicked="onBuy"
      @add-cart="onAddCart"
      @sku-selected="onSkuSelected"
      @stepper-change="onStepperChange"
    >
      <!-- 自定义 sku-header-price -->
      <template slot="sku-header-price" slot-scope="props">
        <div v-if="goods.priceType === 1 || goods.priceType === undefined" class="van-sku__goods-price">
          <span class="van-sku__price-symbol">￥</span><span class="van-sku__price-num">{{ skuData.price | yuan}}</span>
        </div>
        <div v-else-if="goods.priceType === 2" class="van-sku__goods-price">
          <span class="van-sku__price-num">{{ skuData.pointPrice }}积分</span>
        </div>
        <div v-else class="van-sku__goods-price">
          <span class="van-sku__price-symbol">￥</span><span class="van-sku__price-num">{{ skuData.price | yuan}}</span>
          <span class="van-sku__price-num">+{{ skuData.pointPrice }}积分</span>

        </div>
      </template>
    </van-sku>
  </div>
</template>

<script>
import { addCart } from '@/api/cart'
import _ from 'lodash'
import { mapGetters } from 'vuex'

export default {
  props: {
    value: {
      type: Boolean,
      default: false
    },
    skuData: {
      type: Object,
      default() {
        return {}
      }
    },
    goods: {
      type: Object,
      default() {
        return {}
      }
    },
    initialSku: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  computed: {
    ...mapGetters(['userInfo']),
    isShow: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('input', val)
      }
    }
  },
  mounted(){
    console.log('this.skuData',this.skuData)
  },
  methods: {
    onBuy(data) {
      console.log(data)
      if (this.goods.priceType === 2 || this.goods.priceType === 3) {
        if (this.userInfo.userPoint < this.skuData.price) {
          return this.$toast.fail('积分不足')
        }
      }
      if(this.validateSkuData(data) == false){
        return false
      }
      addCart(this.validateSkuData(data)).then(() => {
        this.$router.push({ name: 'Cart' })
      })
    },
    onAddCart(data) {
      if (this.goods.priceType === 2 || this.goods.priceType === 3) {
        if (this.userInfo.userPoint < this.skuData.price) {
          return this.$toast.fail('积分不足')
        }
      }
      if(this.validateSkuData(data) == false){
        return false
      }
      addCart(this.validateSkuData(data)).then(() => {
        this.$toast({
          message: '已添加至购物车',
          duration: 1500
        })
        this.$emit('input', false)
        this.$emit('getNum')
      })
    },
    // 校验sku数据
    validateSkuData(data) {
      console.log('添加购物车==', data)
      const selectedSkuComb = data.selectedSkuComb
      console.log('添加购物车==', selectedSkuComb)

      let productId = 0
      
      this.skuData.list.forEach(element => {
        let spec = element.spec
        let length = spec.length
        for(let i=1;i<=length;i++){
          if(selectedSkuComb['s'+i] == spec[i-1]){
            if(i == length){
              productId = element.id
              break;
            }else if(selectedSkuComb['s'+i] == undefined){
              this.$toast.fail('规格未选完')
            } else {
              continue
            }
          }
        }
        console.log(element)
        // if(selectedSkuComb.hasOwnProperty('s1')){
        //   if(selectedSkuComb.hasOwnProperty('s2')){
        //     if(selectedSkuComb.s1 == element.s1 && selectedSkuComb.s2 == element.s2){
        //       productId = element.id
        //     }
        //   }else{
        //     if(selectedSkuComb.s1 == element.s1){
        //       productId= element.id
        //     }
        //   }

        // }
      });
      console.log('选择的ID',productId)
      const params = {
        goodsId: data.goodsId,
        number: data.selectedNum,
        productId,
        price: data.selectedSkuComb.price  === undefined ? this.skuData.price :(data.selectedSkuComb.price / 100)
      }
      console.log(this.skuData.price)
      // if(params.price== null || params.price ==NaN){
      //   params.price = this.skuData.price
      // }
      console.log('添加购物车==', params)

      if (_.has(data.selectedSkuComb, 's3')) {
        this.$toast({
          message: '目前仅支持两规格',
          duration: 1500
        })
        return false
      } else if (_.has(data.selectedSkuComb, 's2')) {
        params.productId = this.getProductId(
          data.selectedSkuComb.s1,
          data.selectedSkuComb.s2
        )
      } else {
        params.productId = this.getProductIdByOne(data.selectedSkuComb.s1)
      }
      return params
    },
    onSkuSelected(options) {
      console.log(options)
      const { skuValue, selectedSku, selectedSkuComb } = options
      this.$emit('initSku', { skuValue, selectedSku })
    },
    onStepperChange(num) {
      this.$emit('initSkuNum', num)
    },
    getProductId(s1, s2) {
      var productId
      var s1Name
      var s2Name
      _.each(this.goods.specificationList, specification => {
        _.each(specification.valueList, specValue => {
          if (specValue.id === s1) {
            s1Name = specValue.value
          } else if (specValue.id === s2) {
            s2Name = specValue.value
          }
        })
      })

      _.each(this.goods.productList, v => {
        const result = _.without(v.specifications, s1Name, s2Name)
        if (result.length === 0) {
          productId = v.id
        }
      })
      return productId
    },
    getProductIdByOne(s1) {
      var productId
      var s1Name
      _.each(this.goods.specificationList, (specification) => {
        _.each(specification.valueList, (specValue) => {
          if (specValue.id === s1) {
            s1Name = specValue.value
          }
        })
      })

      _.each(this.goods.productList, (v) => {
        const result = _.without(v.specifications, s1Name)
        if (result.length === 0) {
          productId = v.id
        }
      })
      return productId
    }
  }
}
</script>

<style lang="scss">
@import "@/styles/variables.scss";

// reset vant style
.goods-sku {
  .van-sku-messages {
    padding: 0;
  }
  .van-button--danger {
    background: $red;
  }
}
</style>
